<template>
    <div class="koi-flex">
        <KoiCard>

            <el-form v-show="showSearch" :inline="true">
                <el-form-item label="小程序名称" prop="name">
                    <el-input placeholder="请输入小程序名称" v-model="searchParams.name" clearable style="width: 200px"
                        @keyup.enter.native="handleListPage"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
                    <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格头部按钮 -->
            <el-row :gutter="10">
                <el-col :span="1.5">
                    <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
                </el-col>
                <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
            </el-row>

            <br />
            <!-- 数据表格 -->
            <el-table v-loading="loading" border :data="tableList" empty-text="暂时没有数据哟🌻">

                <el-table-column label="小程序名称" prop="name" align="center"
                    :show-overflow-tooltip="true"></el-table-column>

                <el-table-column label="appid" prop="appid" align="center"
                    :show-overflow-tooltip="true"></el-table-column>

                <el-table-column label="小程序密钥" prop="secret" align="center"
                    :show-overflow-tooltip="true"></el-table-column>

                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <el-tooltip content="修改" placement="top">
                            <el-button type="warning" icon="Edit" circle plain @click="handleEdit(row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <br />

            <!-- 分页 -->
            <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
                v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleListPage" @current-change="handleListPage" />

            <KoiDialog ref="koiDialogRef" :title="title" @koiConfirm="handleConfirm" @koiCancel="handleCancel"
                :loading="confirmLoading">
                <template #content>
                    <el-form ref="formRef" :rules="rules" :model="form" label-width="110px">
                        <el-row>
                            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                                <el-form-item label="小程序名称" prop="name">
                                    <el-input v-model="form.name" placeholder="请输入小程序名称" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                                <el-form-item label="小程序appid" prop="appid">
                                    <el-input v-model="form.appid" placeholder="请输入小程序appid" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                                <el-form-item label="小程序密钥" prop="secret">
                                    <el-input v-model="form.secret" placeholder="请输入小程序密钥" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </template>
            </KoiDialog>

        </KoiCard>
    </div>
</template>

<script setup lang="ts" name="wxAppletPage">
import { ref, onMounted, reactive, nextTick } from "vue";
// @ts-ignore
import { koiNoticeSuccess, koiNoticeError, koiMsgWarning, koiMsgBox, koiMsgInfo, koiMsgError } from "@/utils/koi.ts";
// @ts-ignore
import { koiDatePicker } from "@/utils/index.ts";
// @ts-ignore
import { getOperInfo } from "@/api/system/operlog/index.ts";
import { deleteWxApplet, getWxAppletList, addWxApplet, updateWxApplet } from "@/api/system/wxApplet";

// 数据表格加载页面动画
const loading = ref(false);
// 数据表格数据
const tableList = ref<any>([]);

const showSearch = ref<boolean>(true); // 默认显示搜索条件

// 查询参数
const searchParams = ref({
    page: 1, // 第几页
    pageSize: 10, // 每页显示多少条
    name: ''
});
const total = ref<number>(0);

/** 数据表格 */
const handleListPage = async () => {
    try {
        loading.value = true;
        tableList.value = []; // 重置表格数据

        function removeEmptyKeys(obj: any) {
            Object.keys(obj.value).forEach(key => {
                if (obj.value[key] === "" || obj.value[key] === null || obj.value[key] === undefined) {
                    delete obj.value[key];
                }
            });
        }

        removeEmptyKeys(searchParams);

        const res: any = await getWxAppletList(searchParams.value);
        tableList.value = res.data;
        total.value = res.count;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    } finally {
        loading.value = false;
    }
};

// 重置搜索参数
const resetSearchParams = () => {
    searchParams.value = {
        page: 1,
        pageSize: 10,
        name: ''
    };
};

/** 搜索 */
const handleSearch = () => {
    searchParams.value.page = 1;
    handleListPage();
};

/** 重置 */
const resetSearch = () => {
    resetSearchParams();
    handleListPage();
};

onMounted(() => {
    // 获取数据表格数据
    handleListPage();
});

const title = ref('')
const koiDialogRef = ref()
const formRef = ref<any>();
const id = ref('')

/** 清空表单数据 */
const resetForm = () => {
    // 等待 DOM 更新完成
    nextTick(() => {
        if (formRef.value) {
            // 重置该表单项，将其值重置为初始值，并移除校验结果
            formRef.value.resetFields();
        }
    });
    form.value = {
        name: '',
        appid: '',
        secret: ''
    };
    id.value = ''
};

const handleConfirm = () => {
    if (!formRef.value) return;
    confirmLoading.value = true;
    (formRef.value as any).validate(async (valid: any) => {
        if (valid) {

            if (form.value.appid && form.value.appid != null) {
                // 修改

                try {
                    await updateWxApplet(id.value, form.value);
                    koiNoticeSuccess("修改成功🌻");
                    koiDialogRef.value.koiQuickClose();
                    resetForm();
                } catch (error) {
                    koiNoticeError("修改失败，请刷新重试🌻");
                } finally {
                    confirmLoading.value = false;
                }

            } else {
                // 添加
                try {
                    await addWxApplet(form.value);
                    koiNoticeSuccess("添加成功🌻");
                    koiDialogRef.value.koiQuickClose();
                    resetForm();
                } catch (error) {
                    koiNoticeError("添加失败，请刷新重试🌻");
                } finally {
                    confirmLoading.value = false;
                }
            }

        } else {
            koiMsgError("验证失败，请检查填写内容");
            confirmLoading.value = false;
        }
    })
}

const handleCancel = () => {
    koiDialogRef.value.koiClose();
}

const confirmLoading = ref(false);

const form = ref({
    name: '',
    appid: '',
    secret: ''
})

const rules = reactive({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    appid: [
        { required: true, message: '请输入appid', trigger: 'blur' },
    ],
    secret: [
        { required: true, message: '请输入secret', trigger: 'blur' },
    ]
})

const handleEcho = (row: any) => {
    id.value = row.id
    form.value.appid = row.appid
    form.value.name = row.name
    form.value.secret = row.secret
};

const handleAdd = () => {
    resetForm();
    title.value = "添加小程序";
    koiDialogRef.value.koiOpen();
};

const handleEdit = (row: any) => {
    resetForm();
    title.value = "修改小程序";
    handleEcho(row);
    koiDialogRef.value.koiOpen();
};

const handleDelete = (row: any) => {
    koiMsgBox("您确认需要删除小程序名称[" + row.name + "]么？")
        .then(async () => {
            try {
                await deleteWxApplet(row.id)
                handleListPage();
                koiNoticeSuccess("删除成功");
            } catch (error) {
                handleListPage();
                koiNoticeError("删除失败，请刷新重试");
            }
        })
};
</script>

<style lang="scss" scoped></style>